package org.lim.lcpicturebackend.manager.websocket.service;

import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import org.lim.lcpicturebackend.manager.websocket.model.PictureEditRequestMessage;
import org.lim.lcpicturebackend.manager.websocket.model.PictureEditResponseMessage;
import org.lim.lcpicturebackend.manager.websocket.model.enums.PictureEditMessageTypeEnum;
import org.lim.lcpicturebackend.manager.websocket.service.strategy.PictureEditMessageStrategy;
import org.lim.lcpicturebackend.manager.websocket.service.strategy.PictureEditMessageStrategyFactory;
import org.lim.lcpicturebackend.model.entity.User;
import org.lim.lcpicturebackend.service.UserService;
import org.springframework.stereotype.Service;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;

import javax.annotation.Resource;

@Service
@Slf4j
public class PictureEditMessageService {

    @Resource
    private PictureEditMessageStrategyFactory strategyFactory;
    
    @Resource
    private UserService userService;

    /**
     * 处理图片编辑消息
     * @param requestMessage 请求消息
     * @param session WebSocket会话
     * @param user 用户信息
     * @param pictureId 图片ID
     */
    public void handleMessage(PictureEditRequestMessage requestMessage, WebSocketSession session, User user, Long pictureId) throws Exception {
        String type = requestMessage.getType();
        
        try {
            PictureEditMessageTypeEnum messageTypeEnum = PictureEditMessageTypeEnum.valueOf(type);
            
            // 获取对应的策略并执行
            PictureEditMessageStrategy strategy = strategyFactory.getStrategy(messageTypeEnum);
            if (strategy != null) {
                strategy.handleMessage(requestMessage, session, user, pictureId);
            } else {
                handleUnknownMessageType(session, user);
            }
            
        } catch (IllegalArgumentException e) {
            log.warn("无效的消息类型: {}", type, e);
            handleUnknownMessageType(session, user);
        }
    }
    
    /**
     * 处理未知消息类型
     */
    private void handleUnknownMessageType(WebSocketSession session, User user) throws Exception {
        PictureEditResponseMessage responseMessage = new PictureEditResponseMessage();
        responseMessage.setType(PictureEditMessageTypeEnum.ERROR.getValue());
        responseMessage.setMessage("消息类型错误");
        responseMessage.setUser(userService.getUserVO(user));
        session.sendMessage(new TextMessage(JSONUtil.toJsonStr(responseMessage)));
    }
}